package com.yxy.service.Impl;

import com.yxy.common.Const;
import com.yxy.common.ServerResponse;
import com.yxy.common.TokenCache;
import com.yxy.dao.UserMapper;
import com.yxy.entity.User;
import com.yxy.service.IUserService;
import com.yxy.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * UserService的实现
 *
 * @author DengWenJun
 * @cerateTime 2017-08-01-10:41
 **/
@Service("iUservice")
@Transactional
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;


    /**
     * 用户登录
     * @param phone
     * @param password
     * @return
     */
    public User login(String phone, String password) {
        return userMapper.selectLogin(phone, password);

    }


    public int register(User user){
        return userMapper.insert(user);
    }
    public boolean checkValid(String str,String type) {

        if (StringUtils.isNoneBlank(type)) {
            if (Const.PHONE.equals(type)) {
                int resultCount = userMapper.checkPhone(str);
                return resultCount > 0;
            }
            if (Const.EMAIL.equals(type)) {
                int resultCount = userMapper.checkEmail(str);
                return resultCount > 0;
            }
        }
        return false;
    }




    public ServerResponse<String> forgetRestPassWord(String phone,String passwordNew,String forgetToken){
        if (StringUtils.isBlank(forgetToken)){
            return ServerResponse.createByErrorMessage("参数错误，token需要传递");
        }
        boolean validPhone = this.checkValid(phone,Const.USERNAME);
        if (validPhone){
            //用户不存在
            return  ServerResponse.createByErrorMessage("用户不存在");
        }
        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX+phone);
        if (StringUtils.isBlank(token)){
            return ServerResponse.createByErrorMessage("token无效或过期");
        }
        if (StringUtils.equals(forgetToken,token)){
            String md5Password = MD5Util.MD5EncodeUtf8(passwordNew);
            int rowCount = userMapper.updatePasswordByPhone(phone,md5Password);
            if (rowCount>0){
                return ServerResponse.createBySuccessMessage("密码修改成功");
            }
        }else{
            return ServerResponse.createByErrorMessage("token错误，请重新获取");
        }
        return ServerResponse.createByErrorMessage("修改密码失败");
    }


     public boolean updateByPrimaryKey(User record){

        int count = userMapper.updateByPrimaryKeySelective(record);
        return count>0;
   }


    //验证手机号是否注册
    public int checkPhone(String phone){
        return userMapper.checkPhone(phone);
    }

    //用户获取个人信息
    public User getUserInfo(Integer id){
       return userMapper.selectByPrimaryKey(id);
    }

    public List<User> selectJoinSportPerson(Integer sportId){
        return userMapper.selectJoinSportPerson(sportId);
    }


    public boolean insertContactPerson(Integer userId,Integer toUserId){
        int count = userMapper.insertContactPerson(userId,toUserId);
        return count>0;
    }

    public boolean deleteContactPerson(Integer userId,Integer toUserId){
        int count = userMapper.deleteContactPerson(userId,toUserId);
        return count>0;
    }

    public  boolean selectContactPerson(Integer userId,Integer toUserId){
        int count = userMapper.selectContactPerson(userId,toUserId);
        return count > 0;
    }

   public List<User> selectContactPersonList(Integer userId){
        List<User> userList= userMapper.selectContactPersonList(userId);
        return userList;
   }

   public User selectUserByPhone(String phone){
        User user = userMapper.selectUserByPhone(phone);
        return user;
   }

    /**
     * 后台管理
     */
    /**
     * 管理员登录
     * @param user
     * @return
     */
    public User AdminLogin(User user){
        return userMapper.AdminLogin(user);
    }


    public List<User> selectAll(){
        return userMapper.selectAll();
    }

    public boolean deleteUserById(Integer id){
        int count = userMapper.deleteByPrimaryKey(id);
        return count>0;
    }

    public User selectUserById(Integer id){
        return userMapper.selectByPrimaryKey(id);
    }

    public List<User> findLikeList(User user){
        return userMapper.findListByEntity(user);
    }

    public ServerResponse<String> resetPassword(String passwordOld,String passwordNew,User user){
        //防止横向越权，要效验一下这个用户的旧密码，一定要指定是这个用户，因为我们会查询一个count(1)，如果不指定id,那么结果就是true啦count>0
        int resultCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld),user.getId());
        if (resultCount == 0){
            return ServerResponse.createByErrorMessage("旧密码错误");
        }
        user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if (updateCount > 0){
            return ServerResponse.createBySuccessMessage("密码更新成功");
        }
        return ServerResponse.createByErrorMessage("密码更新失败");
    }
}
